<?php


namespace app\api\controller\v1;


use app\api\controller\v1\Clue as ClueModel;
use app\common\model\ClueErrorLog;
use app\lib\exception\ParamException;
use Predis\Command\Redis\DUMP;
use think\Db;

/**
 * 15192223322
 * 通用API
 * https://doc.king.cdsxlc.cn/doc/1/
 */
class CommonClue
{

    public function __construct() {

    }

    public function pushClue($mapping,$clue_info,$listPush)
    {

        $apiName='【'.$mapping['api_name'].'】';
        $clue_rule = json_decode($mapping['rule_json'], true);
        $params = [];
        if(!$clue_rule){
            $errMsg=$apiName.'读取商户接收规则失败';
            ClueErrorLog::record($clue_info['clue_id'],$errMsg,$clue_info);
            model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
            throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
        }else{

//            foreach ($clue_rule as $v){
//                $params[$v['curr']] = $clue_info[$v['orig']];
//                if($v['orig'] == 'city'){
//                    $citys = explode('-',$clue_info[$v['orig']]);
//                    $city_info = Db::name('city')->where(['type'=>2,'id'=>$citys[1]])->find();
//                    $params[$v['curr']] = $city_info['name'];
//                }
//            }


            $clue=Db::name('clue')->where('id',$clue_info['id'])->find();
            if(empty($clue['channel_show'])){
                $isAid = Db::name('account')->where('id', $clue['account_id'])->find();
                $clue['channel_show']=$isAid['acc_desc'];
            }

            unset($clue['id']);
            unset($clue['push_time']);
            unset($clue['create_time']);
            unset($clue['update_time']);
            unset($clue['delete_time']);
            unset($clue['err_msg']);
            unset($clue['price']);
            unset($clue['true_price']);
            unset($clue['clue_cost']);
            unset($clue['account_id']);
            unset($clue['is_black']);
            unset($clue['is_not_push']);

            $clue['status']=0;

            $account = Db::name('account')->where('adv_id',$clue_info['adv_id'])->find();
            $clue['source_acc_name'] = $account['acc_name'];
            $clue['source_acc_desc'] = $account['acc_desc'];

            // 手动修改推送城市
            $clue['city'] = $clue_info['city'];

            $params=$clue;

            if ($clue['type'] == 1 || $clue['type'] == 6) { // 百度
                $params['type'] = 6;
            } elseif ($clue['type'] == 2 || $clue['type'] == 5) { // 腾讯
                $params['type'] = 5;
            } elseif ($clue['type'] == 3 || $clue['type'] == 4) { // 抖音
                $params['type'] = 4;
            } elseif ($clue['type'] == 8) { // uc
                $params['type'] = 9;
            } elseif ($clue['type'] == 9) { //快手
                $params['type'] = 10;
            }

            $api_url = $mapping['api_url'];

            // 给妙言系统单独增加 商务管理员姓名
            $params['push_merchant_name'] = \db('merchant')->alias('m')
                    ->join('push p', 'p.mer_id = m.id', 'left')
                    ->where('p.id', $clue_info['push_id'])
                    ->value('m.mer_name');

            // 2. 推送线索
            $res_json = $this->postJson($api_url, $params);
            $res  = json_decode($res_json, true);

            if(!empty($res)){
                $res['params'] = $params;
                if($res['status']!=200){
                    $errMsg=$apiName.'线索推送商户处理失败:'.$res['msg'];
                    ClueErrorLog::record($clue_info['clue_id'],$errMsg,$res);
                    model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$res['msg']]);
                    throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
                }

            }else{
                $errMsg=$apiName.'线索推送商户请求失败';
                ClueErrorLog::record($clue_info['clue_id'],$errMsg,$params);
                model('Clue')->where('id',$clue_info['id'])->update(['err_msg'=>$errMsg]);
                throw new ParamException(['msg'=>$errMsg,'errorCode'=>10001]);
            }

            return $res;
        }
    }


    /**
     * post发送json格式的数据
     */
    public function postJson($url, $data)
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            throw new ParamException(['msg'=>'请求数据不能为空','errorCode'=>10000]);
        }
        $data=json_encode($data,JSON_UNESCAPED_UNICODE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
//            'token:3dcb0d2dba347b40476bc3294c60fdfe' ,

        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }

}